/*---------------------------------------------------------------------------
 * Speculoos, LDAP to objet mapping.
 * Copyright (C) 2006  Norsys and OQube
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Created on Oct 19, 2005
 * --------------------------------------------------------------------------*/
package speculoos.commons.mockldap;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

import javax.naming.CompoundName;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;

/**
 * This class parses a LDIF file and constructs a graph of TestDirContext
 * objects in memory. A LDIF file as the following format:
 * <ul>
 * <li>each line is an attribute /value pair separated by colon </li>
 * <li>each entry starts with a dn attribute and ends with an empty line </li>
 * </ul>
 * 
 * @author nono
 * @version $Id: LDIFParser.java 65 2007-03-19 22:43:27Z trecloux $
 */
public class LDIFParser {

    private Properties nameSyntax = TestDirContext.SYNTAX;

    private int entryCount;

    /**
     * Parse a LDIF formatetted input Stream. This parser assumes all key/value
     * pairs are on ONE line.
     * 
     * @param is
     * @return
     * @throws IOException
     * @throws NamingException
     */
    public TestDirContext parse(InputStream is) throws IOException,
            NamingException {
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line = null;
        TestDirContext entry = null;
        TestDirContext root = null;
        Attribute cur = null;
        int ln = 0;
        String name = null;
        while ((line = rd.readLine()) != null) {
            ln++;
            /* normalize */
            line = line.trim();
            if (!"".equals(line)) {
                /* split attribute/value */
                String[] kv = line.split(":");
                if (kv.length == 1) {
                    /* a continuated attribute value */
                    if (cur == null)
                        // throw new IOException("File format error : non
                        // attribute value at line "+ln);
                        continue;
                    /* append value */
                    String s = (String) cur.remove(0);
                    cur.add(s + kv[0].trim());
                    continue;
                }
                if ("dn".equals(kv[0])) {
                    /* compute name of entry */
                	name = kv[1].trim();
                    Name nam = new CompoundName(kv[1].trim(), nameSyntax);
                    /* find parent */
                    if (root == null)
                        entry = root = new TestDirContext(nam, null);
                    else
                        entry = (TestDirContext) root.createSubcontext(nam);
                    entryCount++;
                    cur = null;
                } else if ("ACL".equals(kv[0])) {
                    /* ignore ACL */
                    continue;
                } else {
                    /*
                     * if attribute is already defined add a new attribute to
                     * list
                     */
                	if (cur != null) {
                        /* add current accumulated attribute to node */
                        Attributes attrs = entry.getAttributes("");
                        Attribute attr = attrs.get(cur.getID());
                        if (attr == null) {
                            attr = cur;
                            attrs.put(attr);
                        } else
                            attr.add(cur.get());
                    }
                    /* reset cur */
                    String attName = kv[0].trim();
                    if ("objectClass".equals(attName)) {
                    	attName = attName.toLowerCase();
                    }
                    cur = new BasicAttribute(attName);
                    cur.add(kv[1].trim());
                }
            } else {
                if (cur != null) {
                    /* add current accumulated attribute to node */
                    Attributes attrs = entry.getAttributes("");
                    Attribute attr = attrs.get(cur.getID());
                    if (attr == null) {
                        attr = cur;
                        attrs.put(attr);
                    } else
                        attr.add(cur.get());
                }

            }
        }
        return root;
    }

    /**
     * @return Returns the entryCount.
     */
    public int getEntryCount() {
        return entryCount;
    }

    /**
     * @param entryCount The entryCount to set.
     */
    public void setEntryCount(int entryCount) {
        this.entryCount = entryCount;
    }
}
